package com.yami.shop.api.utils;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import com.yami.shop.api.config.WeixinConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * 微信工具类
 */
@Slf4j
@Component
public class WeixinUtils {

    @Autowired
    private WeixinConfig weixinConfig;

    /**
     * 通过wx_code获取open_id
     * @param code 微信登录code
     * @return open_id
     */
    public String getOpenIdByCode(String code) {
        if (code == null || code.isEmpty()) {
            throw new RuntimeException("微信code不能为空");
        }

        String appid = weixinConfig.getAppid();
        String secret = weixinConfig.getSecret();

        // 微信获取openid的API
        String url = "https://api.weixin.qq.com/sns/jscode2session";

        Map<String, Object> params = new HashMap<>();
        params.put("appid", appid);
        params.put("secret", secret);
        params.put("js_code", code);
        params.put("grant_type", "authorization_code");

        try {
            String result = HttpUtil.get(url, params);
            log.info("微信code换取openid结果: {}", result);

            JSONObject jsonObject = JSONObject.parseObject(result);

            // 检查是否有错误
            if (jsonObject.containsKey("errcode")) {
                int errCode = jsonObject.getIntValue("errcode");
                String errMsg = jsonObject.getString("errmsg");
                throw new RuntimeException("微信code换取openid失败: " + errMsg + "(" + errCode + ")");
            }

            return jsonObject.getString("openid");
        } catch (Exception e) {
            log.error("微信code换取openid异常", e);
            throw new RuntimeException("微信code换取openid异常: " + e.getMessage());
        }
    }
}
